import React, { Component } from "react";
import { Upload, Button, Icon, message } from "antd";
import { inject, observer } from "mobx-react";
import VideoPlayer from "../components/common/VideoPlayer";
import {
  HUMANBODY,
  DRAWRECT,
  DISTINGUISHFACE,HUMANBODYCANCEL
} from "../service/api/FaceRecognitionApi";
import Swiper from 'swiper/dist/js/swiper.js'
import 'swiper/dist/css/swiper.min.css'
const introduces = [
  {
    icon:
      "https://yl-gateway.oss-cn-beijing.aliyuncs.com/aiMarket/smallIcons/humanBody/web.png",
    title: "轻量级网络",
    desc: "优化压缩过的网络实现毫秒级检测，帮助用户抓住高速行驶的检测目标。"
  },
  {
    icon:
      "https://yl-gateway.oss-cn-beijing.aliyuncs.com/aiMarket/faceRecogition/2.png",
    // title: "多目标检测",
    title: "遮挡车辆检测",
    // desc: "支持画面中数百个车辆对象的检测，包括局部被遮挡的车辆。"
    desc: "支持画面中对车辆对象的检测，包括局部被遮挡的车辆。"
  },
  {
    icon:
      "https://yl-gateway.oss-cn-beijing.aliyuncs.com/aiMarket/faceRecogition/3.png",
    title: "稳定高效",
    desc: "在极端画面条件下仍可以保证高准确率和召回率的输出，确保服务高可用。"
  },
  {
    icon:
      "https://yl-gateway.oss-cn-beijing.aliyuncs.com/aiMarket/smallIcons/caricon.png",
    title: "适配多种车型",
    // desc: "可以检测出普通轿车，运动型实用汽车，公交车，卡车，大中小型货车和环卫车辆等多种车型。"
    desc:
      "可以检测出普通轿车、运动型实用汽车、公交车、卡车、大中小型货车等多种车型。"
  }
];

const videoJsOptions = {
  controls: true,
  loop: true,
  sources: [
    {
      src:
        "https://yl-gateway.oss-cn-beijing.aliyuncs.com/aiMarket/MotorVehicleRecognition/carVideo.mp4",
      type: "video/mp4"
    }
  ]
};

const checkImgList = [
  "https://yl-gateway.oss-cn-beijing.aliyuncs.com/aiMarket/MotorVehicleRecognition/demoPicture1.png",
  "https://yl-gateway.oss-cn-beijing.aliyuncs.com/aiMarket/MotorVehicleRecognition/demoPicture2.png",
  "https://yl-gateway.oss-cn-beijing.aliyuncs.com/aiMarket/MotorVehicleRecognition/demoPicture3.png",
  "https://yl-gateway.oss-cn-beijing.aliyuncs.com/aiMarket/MotorVehicleRecognition/demoPicture4.png"
];

@inject("FaceRecognitionStore")
@observer
export default class componentName extends Component {
  constructor(props) {
    super(props);
  }
  state = {
    checkIndex: 0,
    previewImg: checkImgList[0],
    checkState: false,
    changeImg: undefined,
    queryResult: [],
    scalingRatio: 1, //缩放比例
    uploadImageWidth: undefined,
    divWidth: undefined,
    lastIsUploadImg: false, //点击检测图片之前是上传的图片
    tooBig: false, //上传文件大于1Mb吗
    formatFalse: false, //图片格式错误
    checkImgList: [
      "https://yl-gateway.oss-cn-beijing.aliyuncs.com/aiMarket/MotorVehicleRecognition/demoPicture1.png",
      "https://yl-gateway.oss-cn-beijing.aliyuncs.com/aiMarket/MotorVehicleRecognition/demoPicture2.png",
      "https://yl-gateway.oss-cn-beijing.aliyuncs.com/aiMarket/MotorVehicleRecognition/demoPicture3.png",
      "https://yl-gateway.oss-cn-beijing.aliyuncs.com/aiMarket/MotorVehicleRecognition/demoPicture4.png"
    ],
    latest: 0, //最新点击的
  };
  Framed = (id, data, lineWidthA, strokeStyle, lineWidthB, lineWidthC) => {
    this.calculateRatio(); //先计算比率
    //导出画框函数
    var c = document.getElementById(id);
    var ctx = c.getContext("2d");
    data.map((item, key) => {
      var scalingRatio = this.state.scalingRatio;
      if (this.state.lastIsUploadImg) {
        item.l =
          item.l * scalingRatio +
          (1004 - this.getDivWidthAndHeight("the_uploadedImg")[0]) / 2;
        item.t = item.t * scalingRatio;
        item.w = item.w * scalingRatio;
        item.h = item.h * scalingRatio;
      }
      //canvas绘图
      ctx.beginPath();
      ctx.lineWidth = lineWidthA;
      ctx.strokeStyle = strokeStyle;
      ctx.rect(item.l, item.t, item.w, item.h);
      ctx.stroke();
      //   ctx.beginPath();
      //   ctx.lineWidth = lineWidthB;
      //   ctx.moveTo(item.l, item.t + lineWidthB / 2);
      //   ctx.lineTo(item.l + item.w / 4, item.t + lineWidthB / 2);

      //   ctx.moveTo(item.l + item.w, item.t + lineWidthB / 2);
      //   ctx.lineTo(item.l + item.w - item.w / 4, item.t + lineWidthB / 2);

      //   ctx.moveTo(item.l, item.t + item.h - lineWidthB / 2);
      //   ctx.lineTo(item.l + item.w / 4, item.t + item.h - lineWidthB / 2);

      //   ctx.moveTo(item.l + item.w, item.t + item.h - lineWidthB / 2);
      //   ctx.lineTo(
      //     item.l + item.w - item.w / 4,
      //     item.t + item.h - lineWidthB / 2
      //   );

      //   ctx.moveTo(item.l + lineWidthB / 2, item.t);
      //   ctx.lineTo(item.l + lineWidthB / 2, item.t + item.h / 4);

      //   ctx.moveTo(item.l + lineWidthB / 2, item.t + item.h);
      //   ctx.lineTo(item.l + lineWidthB / 2, item.t + item.h - item.h / 4);

      //   ctx.moveTo(item.l + item.w - lineWidthB / 2, item.t);
      //   ctx.lineTo(item.l + item.w - lineWidthB / 2, item.t + item.h / 4);

      //   ctx.moveTo(item.l + item.w - lineWidthB / 2, item.t + item.h);
      //   ctx.lineTo(
      //     item.l + item.w - lineWidthB / 2,
      //     item.t + item.h - item.h / 4
      //   );

      ctx.stroke();
      //   //绘制完四边框条条
      //   //在人体图片框上面弄一个说明
      //   ctx.beginPath();
      //   ctx.lineWidth = lineWidthC;
      //   ctx.fillStyle = strokeStyle;
      //   ctx.fillRect(item.l, item.t - 20, 40, 20);
      //   ctx.stroke();
      //   //说明结束
      //   //写上字
      //   //创建渐变
      //   var grad = ctx.createLinearGradient(0, 0, c.width, 0);
      //   ctx.font = "bold 14px arial";
      //   ctx.fillStyle = "blue";
      //   //横排文字
      //   ctx.strokeStyle = grad;
      //   ctx.fillText(item.txt, item.l, item.t - 5, 40);
      //   ctx.strokeText(item.txt, 40, 20, 40);
      //   //
    });
  };
  getDivWidthAndHeight = id => {
    var img = document.getElementById(id);
    var result = [];
    result.push(window.getComputedStyle(img).width);
    result.push(window.getComputedStyle(img).height);
    result[0] = result[0].split("px")[0];
    result[1] = result[1].split("px")[0];
    return result;
  };
  calculateRatio = () => {
    this.setState(() => ({
      scalingRatio:
        parseFloat(this.getDivWidthAndHeight("the_uploadedImg")[0]) /
        parseFloat(this.state.uploadImageWidth)
    }));
  };
  //   calculateRatio = async () => {
  //     await this.getDivWidthAndHeight;

  //     console.log(parseFloat(this.state.divWidth));
  //     console.log(parseFloat(this.state.uploadImageWidth));
  //     console.log(
  //       parseFloat(this.state.divWidth) / parseFloat(this.state.uploadImageWidth)
  //     );
  //     this.setState(() => ({
  //       scalingRatio:
  //         parseFloat(this.state.divWidth) /
  //         parseFloat(this.state.uploadImageWidth)
  //     }));
  //   };
  getUploadImageWidthAndHeight = url => {
    var that = this;
    var img = new Image();
    img.src = url;
    var result = [];
    img.onload = function() {
      result[0] = img.width;
      result[1] = img.height;
      that.setState(() => ({
        uploadImageWidth: result[0]
      }));
    };
  };

  //   getUploadImageWidthAndHeight = url => {
  //     var that = this;
  //     var img = new Image();
  //     img.src = url;
  //     var result = [];
  //     img.onload = function() {
  //       result[0] = img.width;
  //       result[1] = img.height;
  //       that.setState(() => ({
  //         uploadImageWidth: result[0]
  //       }));
  //     };
  //     return result;
  //   };
  //   renderCheckImgList = () => {
  //     const { changeImg } = this;
  //     const { checkIndex } = this.state;
  //     return this.state.checkImgList.map((item, key) => {
  //       // console.log(item.indexOf('base64'))
  //       var ListLength = this.state.checkImgList.length;
  //       let className = "yl-ai-body-text-simple-img";
  //       if (checkIndex == key) {
  //         className += " img-change";
  //       }
  //       return (
  //         <div
  //           onClick={() => {
  //             changeImg(key, ListLength);
  //           }}
  //           className={className}
  //           key={"img_" + key}
  //         >
  //           <img title="" alt="" src={item} />
  //         </div>
  //       );
  //     });
  //   };
  clearRect = () => {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.clearRect(0, 0, 1004, 502);
  };
  changeImg = (i, ListLength) => {
    this.clearRect();
    this.setState(() => ({
      //点击之前默认清空所有状态
      formatFalse: false,
      tooBig: false
    }));
    if (ListLength > 4) {
      if (i >= ListLength - 4 && i < ListLength) {
        //如果点击的是最后四个数组执行原来的方法
        this.setState({
          queryResult: [],
          checkIndex: i,
          checkState: false,
          previewImg: this.state.checkImgList[i],
          lastIsUploadImg: false
        });
      } else {
        //如果点击的是上传的第几个图片
        this.setState({
          queryResult: [],
          checkIndex: i,
          checkState: false,
          previewImg: this.state.checkImgList[i],
          lastIsUploadImg: true
        });
      }
    } else {
      this.setState({
        queryResult: [],
        checkIndex: i,
        checkState: false,
        previewImg: this.state.checkImgList[i],
        lastIsUploadImg: false
      });
    }
  };
  //   changeImg = (i, ListLength) => {
  //     this.clearRect();
  //     this.setState(() => ({
  //       //点击之前默认清空所有状态
  //       formatFalse: false,
  //       tooBig: false
  //     }));
  //     // console.log(i)   ListLength=6
  //     if (ListLength > 4) {
  //       if (i >= ListLength - 4 && i < ListLength) {
  //         //如果点击的是最后四个数组执行原来的方法
  //         this.setState({
  //           queryResult: [],
  //           checkIndex: i,
  //           checkState: false,
  //           previewImg: this.state.checkImgList[i],
  //           lastIsUploadImg: false
  //         });
  //       } else {
  //         //如果点击的是上传的几个图片
  //         this.setState({
  //           queryResult: [],
  //           checkIndex: i,
  //           checkState: false,
  //           previewImg: this.state.checkImgList[i],
  //           lastIsUploadImg: true
  //         });
  //       }
  //     } else {
  //       this.setState({
  //         queryResult: [],
  //         checkIndex: i,
  //         checkState: false,
  //         previewImg: this.state.checkImgList[i],
  //         lastIsUploadImg: false
  //       });
  //     }
  //   };

  checkQuery = url => {
    this.setState({
      checkState: true
    });
    const _that = this;
    const { previewImg, changeImg } = this.state;
    const formData = new FormData();
    let imgUrl = url;

    if (typeof imgUrl == "string" && imgUrl.length > 200) {
      imgUrl = imgUrl.replace("data:image/png;base64,", "base64://");
      imgUrl = imgUrl.replace("data:image/jpg;base64,", "base64://");
      imgUrl = imgUrl.replace("data:image/jpeg;base64,", "base64://");
    }
    formData.append("src", imgUrl);
    formData.append("typs", "car,truck,bus");

    HUMANBODY(formData).then(rss => {
      console.log(rss);
      if (rss.code == 200) {
        rss.data = rss.data || [];
        const marks = rss.data.map((vl, ket) => {
          const value = [vl.l, vl.t, vl.w, vl.h];
          rss.data[ket].txt = `机动车:${ket + 1}`; //给data添加属性txt表示是哪一辆车
          return {
            color: [24, 144, 255],
            box: value,
            txt: `机动车:${ket + 1}`
          };
        });
        // rs.data = this.filterLessThan(rs.data, 55); //过滤小于55分的数据
        console.log(rss.data);
        _that.setState({
          checkState: undefined,
          queryResult: rss.data
        });
        this.Framed("myCanvas", rss.data, "1", "#00B9EF", "4", "2");
        this.setState(() => ({
            latest: this.state.latest-1
        }));
        formData.append("marks", JSON.stringify(marks));
        // DRAWRECT(formData).then(rs => {
        //   if (rs.code == 200) {
        //     _that.setState({
        //       checkState: undefined,
        //       previewImg: "data:image/jpg;base64," + rs.data.b64
        //     });
        //   }
        //   console.info(rs, "获取画框后的图片");
        // });
      } else {
        // message.warning("请检查上传数据源是否含有人员头像信息！");
      }
    });
  };
  filterLessThan(arr, howmany) {
    arr = arr.filter(item => {
      return item.score > howmany;
    });
    return arr;
  }

  componentDidMount() {
    window.scrollTo(0, 0);
    var mySwiper = new Swiper(".swiper-container", {
      //swiper的配置
      slidesPerView: 4,
      spaceBetween: 10,
      initialSlide: this.state.slide_to_index,
      speed: 500,
      nextButton: '.swiper-button-next',
      prevButton: '.swiper-button-prev',
      on: {
        slideChange: function() {
          console.log(localStorage.getItem("index"));
        }
      }
    });
  }
  render() {
    const _that = this;
    const { checkQuery } = this;
    const { previewImg, checkState, queryResult } = this.state;
    const uploadProps = {
      beforeUpload(e) {
        _that.setState(() => ({
          //点击之前默认清空所有状态
          formatFalse: false,
          tooBig: false
        }));

        var file_onload_promise = new Promise((resolve, reject) => {
          const file = e;
          var fr = new FileReader();
          fr.onload = () => {
            const fileType = "image/pngimage/jpgimage/jpeg";
            if (fileType.indexOf(file.type) < 0) {
              _that.setState(() => ({
                formatFalse: true
              }));
              return false;
            } else if (file.size > 1024 * 1024 * 5) {
              _that.setState(() => ({
                tooBig: true,
                formatFalse: false
              }));
              return false;
            } else {
              var dataURL = fr.result; // picture_base64
              _that.state.checkImgList.unshift(dataURL);
              _that.setState(
                {
                  queryResult: [],
                  openCamera: false,
                  checkIndex: -1,
                  checkState: false,
                  previewImg: dataURL,
                  lastIsUploadImg: true,
                  tooBig: false,
                  formatFalse: false,
                  checkImgList: _that.state.checkImgList,
                  firstImgBase64: dataURL
                },
                res => {
                  resolve("ok");
                }
              );
            }
          };
          fr.readAsDataURL(file);
        });
        file_onload_promise.then(res => {
          if (res === "ok") {
            _that.getDivWidthAndHeight("the_uploadedImg");
            _that.getUploadImageWidthAndHeight(_that.state.previewImg);
            _that.checkQuery(_that.state.previewImg);
            _that.setState(() => ({
              slide_to_index: 0
            }));
          }
        });
      }
    };
     new Swiper(".swiper-container", {
      //swiper的配置
      slidesPerView: 4,
      spaceBetween: 10,
      initialSlide: this.state.slide_to_index,
      speed: 500,
      nextButton: '.swiper-button-next',
      prevButton: '.swiper-button-prev',
      on: {
        slideChange: function() {
          console.log(localStorage.getItem("index"));
        }
      }
    });
    return (
      <div className="yl-ai-body-container">
        <div className="yl-ai-body-banner yl-ai-motorVehicleRecognition">
          <div className="yl-ai-banner-opicity"></div>
          <div className="yl-ai-banner-txt">
            <div className="yl-ai-banner-title">机动车识别</div>
            <div className="yl-ai-banner-desc">
              {/* 具备毫秒级检测高速行驶的多个目标，一个算法支持轿车、公交车、卡车、大中小型货车等多种类型车辆识别，在1080P画面下具备同时检出数百车辆的能力。 */}
              机动车识别通过实时检测图像或视频流中的所有机动车并为车辆打框，支持毫秒级检测高速行驶的多个目标，一个算法支持轿车、公交车、卡车、大中小型货车等多种类型车辆的识别。
            </div>
          </div>
        </div>

        <div className="yl-ai-body-container">
          <div className="yl-ai-body-container-panel">
            <div className="yl-ai-body-title">产品亮点</div>
            <div className="yl-ai-body-max-width">
              <div className="yl-ai-body-introduces">
                {introduces.map((item, key) => {
                  return (
                    <div className="yl-ai-body-introduce">
                      <div className="yl-ai-body-introduce-icon">
                        <img src={item.icon} />
                      </div>
                      <div className="yl-ai-body-introduce-text">
                        <div className="yl-ai-body-introduce-title">
                          {item.title}
                        </div>
                        <div className="yl-ai-body-introduce-desc">
                          {item.desc}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>

          <div className="yl-ai-body-container-panel">
            <div className="yl-ai-body-title  " >功能演示</div>
            <div className="yl-ai-body-max-width">
              <div className="yl-ai-body-test-simple">
                <div className="yl-ai-body-test-simple-left">
                  <div className="yl-ai-body-text-simple-img-change">
                    {checkState && <div className="scan-panel"></div>}
                    {/* <Upload {...uploadProps}>
                      <div
                        className="load-button"
                        onClick={() => {
                          this.clearRect();
                        }}
                      >
                        <div className="yl-ai-check-button">上传图片</div>
                      </div>
                    </Upload> */}
                    <canvas id="myCanvas" width="1004" height="502px"></canvas>
                    <img
                      className="uploadedImg"
                      id="the_uploadedImg"
                      src={previewImg}
                      alt=""
                      title=""
                    />
                    <div className="yl-ai-body-text-simple-img-change-toast">
                    <Upload {...uploadProps}>
                        <div
                          className="human_uoload_img"
                          onClick={() => {
                            this.clearRect();
                          }}
                        >
                          <Button type="primary"> 上传图片</Button>
                        </div>
                      </Upload>
                      <div className="yl-ai-body-text-simple-imgs-message">
                        图片文件类型支持jpg、jpeg、png，图片大小不超过5M
                      </div>
                    </div>
                    <div
                      className="warining"
                      style={{ display: this.state.tooBig ? "block" : "none" }}
                    >
                      文件超过5MB，不支持上传
                    </div>
                    <div
                      className="warining"
                      style={{
                        display: this.state.formatFalse ? "block" : "none"
                      }}
                    >
                      仅支持jpg，jpeg，png格式
                    </div>
                    {/* 不要在css里设置画布大小否则会等比例缩放导致位置不精确 */}
                  </div>
                  <div className="yl-ai-body-text-simple-imgs">
                    {/* 下面是swiper */}
                    {/* <AwesomeSwiper
                      ref={ref => (this.swiperRef = ref)}
                      config={config}
                      className="swiper-slide-k"
                    >*/}
                    <div class="swiper-container">
                      <div className="swiper-wrapper">
                        {this.state.checkImgList.map((item, key) => {
                          var ListLength = this.state.checkImgList.length;
                          let className = "yl-ai-body-text-simple-img";
                          if (this.state.checkIndex == key) {
                            className += " img-change";
                          }
                          return (
                            <div className="swiper-slide">
                              <div
                                onClick={() => {
                                  let changeImgPromise = new Promise(
                                    (resolve, reject) => {
                                      this.changeImg(key, ListLength);
                                      var recordIndex = index => {
                                        this.setState(() => ({
                                          slide_to_index: index,
                                          latest:this.state.latest+1
                                        }));
                                      };
                                      recordIndex(key);
                                      resolve("ok");
                                    }
                                  );
                                  changeImgPromise.then(() => {
                                    this.getDivWidthAndHeight(
                                      "the_uploadedImg"
                                    );
                                    this.getUploadImageWidthAndHeight(
                                      this.state.previewImg
                                    );
                                    if(this.state.latest>1){
                                        HUMANBODYCANCEL(this.state.last_formData, "post");
                                    }
                                    this.checkQuery(this.state.previewImg);
                                  });
                                }}
                                className={className}
                                key={"img_" + key}
                              >
                                <img title="" alt="" src={item} />
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    </div>
                    <div className="swiper-button-prev"></div>
                    <div className="swiper-button-next"></div>
                    {/*    </AwesomeSwiper>*/}
                  </div>
                </div>
                <div className="yl-ai-body-test-simple-right">
                  <div className="yl-ai-body-test-result-line">
                    <img src="https://yl-gateway.oss-cn-beijing.aliyuncs.com/aiMarket/smallIcons/carIconImg.png" />
                    <span>{(queryResult && queryResult.length) || 0}辆</span>
                  </div>

                  {queryResult.map((item, key) => {
                    return (
                      <div key={key} className="yl-ai-body-test-result-line">
                        <span className="needFloatLeft">{item.txt}</span>
                        <img src="https://yl-gateway.oss-cn-beijing.aliyuncs.com/aiMarket/smallIcons/cameraIcon.png" />
                        <span>{item.score.toFixed(2)}</span>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
          </div>

          <div className="yl-ai-body-container-panel yl-ai-body-app-scene">
            <div className="yl-ai-body-title">应用场景</div>
            <div className="yl-ai-body-max-width ">
              <div className="yl-ai-humanRecognitionTracking-scene">
                <div className="yl-ai-humanRecognitionTracking-scene-desc">
                  <div className="yl-ai-humanRecognitionTracking-scene-title">
                    交通流量检测
                  </div>
                  <div className="yl-ai-humanRecognitionTracking-scene-desc">
                    主要应用于机动车违停检测，越界入侵，交通拥堵态势感知，封闭道路交通流量监测等场景。
                  </div>
                </div>
                <div className="yl-ai-humanRecognitionTracking-scene-video">
                  <VideoPlayer {...videoJsOptions} />
                </div>
              </div>
            </div>
          </div>

          <div className="yl-ai-body-container-panel yl-ai-example-panel">
            <div className="yl-ai-body-title">云粒智慧应用案例</div>
            <div className="yl-ai-body-max-width">
              <div className="yl-ai-examples">
                <div className="yl-ai-example">
                  <div className="yl-ai-example-title title-h2">
                    云防·智慧园区管理平台
                  </div>

                  <div className="yl-ai-example-double-desc"></div>
                  <div className="yl-ai-example-image">
                    <img
                      src="https://yl-gateway.oss-cn-beijing.aliyuncs.com/aiMarket/MotorVehicleRecognition/exampleImg1.png"
                      alt=""
                      title=""
                    />
                  </div>
                  <div className="yl-ai-examples-copyWriting">
                    云防智慧园区管理平台是云粒自主研发的基于人脸识别、车辆识别等视频识别技术的园区综合管理平台，平台由态势感知、异常预警、高级研判、智能检索、智能终端5部分组成，广泛应用于各类园区的综合管控。
                  </div>
                </div>
                <div className="yl-ai-example">
                  <div className="yl-ai-example-title title-h2">
                    云控·交通大脑-交通管控平台
                  </div>

                  <div className="yl-ai-example-double-desc"></div>
                  <div className="yl-ai-example-image">
                    <img
                      src="https://yl-gateway.oss-cn-beijing.aliyuncs.com/aiMarket/MotorVehicleRecognition/exampleImg2.png"
                      alt=""
                      title=""
                    />
                  </div>
                  <div className="yl-ai-examples-copyWriting">
                    云控交通大脑交通管控平台是由云粒自主研发的基于机器视觉的交通管理平台，该平台能够识别道路拥堵、车辆事故，支持车辆特征布控，车辆行为异常报警等，可对信号灯、卡口设备进行实时调节控制，实现对全域交通的态势感知、指挥调度，实现缓解拥堵，保障交通安全的目标。
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
